import cloud from '@tbmp/mp-cloud-sdk'
const makeupPlugin = require('./pfMakeupPlugin/index')
let util
const log = t => getApp().globalData.logger.log('[App]' + t)

cloud.init({
  env: 'online'
});

App({
  cloud,
  onLaunch(options) {
    // 第一次打开
    // options.query == {number:1}
    console.info('App onLaunch')
    this.globalData.perfectLib = makeupPlugin.getPerfectLib()
    this.globalData.logger = this.globalData.perfectLib.getLogger()
    this.globalData.systemInfo = my.getSystemInfoSync()

    if (!util) {
      util = require('./util')
    }
    
    log(JSON.stringify('systemInfo:' + this.globalData.systemInfo))

    this.initDebugSetting()
    this.initCloud()
    this.globalData.perfectLib.init(
      {
        cloud: this.cloud
      },
      statusCode => {
        log('init result: ' + statusCode);
        if (statusCode !== makeupPlugin.getStatusTable().STATUS_SUCCESS) {
          my.alert({
            content: 'Init error! status code:' + statusCode,
          })
        }
      }
    )
  },

  initDebugSetting() {
    const setting = my.getStorageSync({ key: util.CACHE_KEY_DEBUG_SETTING })
    if (setting && setting.data && setting.data.setting) {
      if (!setting.data.setting.cloudEnv) {
        setting.data.setting.cloudEnv = 'test'
      }
      this.globalData.debugSetting = setting.data.setting
    }

    const hisory = my.getStorageSync({ key: util.CACHE_KEY_LOG_HISTORY })
    if (hisory && hisory.data) {
      this.globalData.logHistory = hisory.data.log
    }

    const dmoain = my.getStorageSync({ key: util.CACHE_KEY_DOMAIN_SETTING })
    if (dmoain && dmoain.data && dmoain.data.setting) {
      this.globalData.domainSetting = dmoain.data.setting
    }

    log('globalData.debugSetting:' + JSON.stringify(this.globalData.debugSetting))
  },

  initCloud() {
    this.cloud.init({
      env: this.globalData.debugSetting.cloudEnv
    })
  },

  onShow(options) {
    // 从后台被 scheme 重新打开
    // options.query == {number:1}
  },

  onError(err) {
    log(`${err.message}\n${JSON.stringify(err)}`)
  },

  onShareAppMessage() {
    return {
      path: 'pages/entry/entry',
      imageUrl: 'http://pf-app-master.oss-cn-beijing.aliyuncs.com/miniprogram/App-Taobao/Makeup/makeup-sdk/img_mk_default.jpg'
    }
  },

  dataMd(type,remark){
    getApp().cloud.function.invoke('client',{ type:type,remark:remark},'buriedPoint').then(res => {
      if(res.code == 200){
        //埋点
        //my.showToast({content:remark})
      }else{
        my.showToast({content:'网络异常'})
      }

    })   
  },

  globalData: {
    systemInfo: {},
    photoWidth: 0,
    photoHeight: 0,
    perfectLib: null,
    featureSetting: {
      enableAllFeatures: false
    },
    debugSetting: {
      cloudEnv: 'online',
      showLogEntry: false
    },
    domainSetting: {
      apiDomainConfig: 'default',
      apiDomainType: 'production'
    },
    logHistory: '',
    takePicture: {
      frame: null
    }
  }
})
